package com.classic.fragment;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.classic.base.LazyLoadFragment;
import com.classic.base.UBaseApplication;
import com.classic.duanzhi.R;

public class UNewsFragment extends LazyLoadFragment {

    WebView webview;
    ProgressBar mProgressBar;
    FrameLayout llTitleLayout;
    TextView back;
    TextView title;

    private static final String SHOW_TITLE = "showTitle";
    private static final String SHOW_BACK = "SHOW_BACK";
    private static final String TITLE = "TITLE";
    private static final String URL = "URL";

    public static UNewsFragment starThis(boolean showTitle, boolean showBack, String title, String url) {
        UNewsFragment uNewsFragment = new UNewsFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(SHOW_TITLE, showTitle);
        bundle.putBoolean(SHOW_BACK, showBack);
        bundle.putString(TITLE, title);
        bundle.putString(URL, url);
        uNewsFragment.setArguments(bundle);
        return uNewsFragment;
    }

    public static UNewsFragment starThis() {
        UNewsFragment uNewsFragment = new UNewsFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(SHOW_TITLE, true);
        bundle.putBoolean(SHOW_BACK, true);
        bundle.putString(TITLE, "新闻");
        bundle.putString(URL, "https://cpu.baidu.com/1022/eb44625e/i?pu=1&promotion_media_channel=27419");
        uNewsFragment.setArguments(bundle);
        return uNewsFragment;
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_unews;
    }

    ImageView home;

    @Override
    protected void initView() {
        mProgressBar = rootView.findViewById(R.id.mProgressBar);
        webview = rootView.findViewById(R.id.webview);
        llTitleLayout = rootView.findViewById(R.id.ll_title_layout);
        back = rootView.findViewById(R.id.iv_title_back);
        title = rootView.findViewById(R.id.tv_title_appname);
        home = rootView.findViewById(R.id.img_web_home);
        rootView.findViewById(R.id.img_web_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webview.goBack();
            }
        });
    }

    @Override
    protected void initData() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!webview.canGoBack()) {
//                    mainActivity.onBack();
                    if (null != listener) listener.onBack();
                }
                webview.goBack();
            }
        });

        webview.getSettings().setJavaScriptEnabled(true);
        webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webview.getSettings().setDomStorageEnabled(true);
        webview.setWebChromeClient(webChromeClient);
        webview.setWebViewClient(webViewClient);
        webview.setFocusable(true);

        WebSettings webSettings = webview.getSettings();
        webSettings.setSupportZoom(true);
        webSettings.setTextZoom(100);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setBuiltInZoomControls(true);
        String appCachePath = UBaseApplication.getInstance().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(appCachePath);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptEnabled(true);//允许使用js
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        webview.setBackgroundColor(0);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        final Bundle arguments = getArguments();
        boolean aBoolean = arguments.getBoolean(SHOW_TITLE);
        boolean ba = arguments.getBoolean(SHOW_BACK);
        llTitleLayout.setVisibility(aBoolean ? View.VISIBLE : View.GONE);
        back.setVisibility(ba ? View.VISIBLE : View.GONE);
        final String string = arguments.getString(URL);
        webview.loadUrl(TextUtils.isEmpty(string) ? "https://cpu.baidu.com/1022/eb44625e/i?pu=1&promotion_media_channel=27419" : string);
        title.setText("新闻");
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webview.loadUrl(TextUtils.isEmpty(string) ? "https://cpu.baidu.com/1022/eb44625e/i?pu=1&promotion_media_channel=27419" : string);
            }
        });
    }


    @Override
    public void fetchData() {

    }

    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
    private WebChromeClient webChromeClient = new WebChromeClient() {
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, JsResult result) {
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext());
            localBuilder.setMessage(message).setPositiveButton("确定", null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();

            //注意:
            //必须要这一句代码:result.confirm()表示:
            //处理结果为确定状态同时唤醒WebCore线程
            //否则不能继续点击按钮
            result.confirm();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgressBar.setProgress(newProgress);
        }
    };
    //WebViewClient主要帮助WebView处理各种通知、请求事件
    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            mProgressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            mProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            webview.loadUrl(url);
            return super.shouldOverrideUrlLoading(view, url);
        }
    };

    /**
     * 返回上一页
     */
    public void goBack() {
        if (null != webview) {
            if (!webview.canGoBack()) {
//                mainActivity.onBack();
                if (null != listener) listener.onBack();
            }
            webview.goBack();
        }
    }

    public BackListener listener;

    public BackListener getListener() {
        return listener;
    }

    public void setListener(BackListener listener) {
        this.listener = listener;
    }

    interface BackListener {
        void onBack();
    }
}
